package controller;

import com.github.pagehelper.PageInfo;
import constant.Constant;
import entity.Resource;
import entity.User;
import exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import service.*;
import util.AjaxResult;
import util.CommonUtil;
import util.DateUtil;
import vo.ResourceVo;
import vo.UserResource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;
import java.util.Properties;

@Controller
@RequestMapping("resource")
public class ResourceController {

    @Autowired
    ResourceService resourceService;
    @Autowired
    UserService userService;
    @Autowired
    GoldPointsService goldPointsService;
    @Autowired
    ChapterService chapterService;
    @Autowired
    UserResourceService userResourceService;

    @RequestMapping("/findBackResource.do")
    @ResponseBody
    public PageInfo<Resource> findBackResource(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Constant.SESSION_USER);
        Integer pageNo = Integer.parseInt(request.getParameter("pageNo"));

        ResourceVo resource = new ResourceVo();
        resource.setUser_id(user.getId());
        resource.setTitle(request.getParameter("title"));
        resource.setUser_name(request.getParameter("user_name"));
        resource.setCreate_start_date(DateUtil.startDate(request.getParameter("create_start_date")));
        resource.setCreate_end_date(DateUtil.endDate(request.getParameter("create_end_date")));
        if (null == request.getParameter("status")) {
            resource.setStatus(Constant.STATUS_ENABLE);
        } else {
            resource.setStatus(Integer.parseInt(request.getParameter("status")));
        }
        resource.setFile_type(request.getParameter("file_type"));
        System.out.println("resource=" + resource);
        PageInfo<Resource> pageInfo = resourceService.queryResource(pageNo, resource);
        return pageInfo;
    }

    //    添加资源
    @RequestMapping("/addFrontResource.do")
    @ResponseBody
    public AjaxResult addFrontResource(Resource resource, MultipartFile multiFiles, HttpSession session) {
        System.out.println(resource);
//        获取文件上传的路径
        CommonUtil.setContext(session.getServletContext());// 设置上下文
        String uploadPath = CommonUtil.getUploadPath();

        File dirfile = new File(uploadPath, Constant.RESOURCE_FILE);
//        资源文件：如果路径不存在，则创建
        if (!dirfile.exists()) {
            dirfile.mkdirs();
        }
//        获取文件名称
        String filename = multiFiles.getResource().getFilename();

//        判断文件是否存在
        File resourceFile = new File(dirfile, filename);
        long start = 0;// 记录资源文件初始位置
        if (resourceFile.exists()) {// 资源文件存在
            start = resourceFile.length();
        }

//        将资源信息添加到数据库
        if (-1 == resource.getChapter_id()) {
            return AjaxResult.isFail("请选择章节");
        }
//        封装resource
        System.out.println("封装resource");
        resource.setClick_count(0);//默认上传的点击量为0
        resource.setPath(Constant.RESOURCE_FILE + "/" + filename);
        resource.setOriginal_name(filename.substring(0,filename.lastIndexOf(".")));
        resource.setFile_size(multiFiles.getSize());
        String[] type = multiFiles.getContentType().split("/");
        resource.setFile_type("." + type[type.length - 1]);
        if (null != session.getAttribute(Constant.SESSION_USER)) {
            User user = (User) session.getAttribute(Constant.SESSION_USER);
            resource.setUser_id(user.getId());
        }
        try {
            if (!resourceService.addFrontResource(resource)) {
                return AjaxResult.isFail("上传失败！");
            }
        } catch (ServiceException e) {
            return AjaxResult.isFail(e.getMessage());
        }
        System.out.println("okkkkkk");
        return AjaxResult.isOk(start);
    }

    // 资源断点续传
    @RequestMapping("/upload.do")
    @ResponseBody
    public AjaxResult upLoadResource(String filename, Long start, MultipartFile file, HttpSession session) {
//        获取文件上传的路径
        CommonUtil.setContext(session.getServletContext());// 设置上下文
        String uploadPath = CommonUtil.getUploadPath();
        File destFile = new File(uploadPath + "/" + Constant.RESOURCE_FILE, filename);

        try {
//        访问文件
            RandomAccessFile randomAccessFile = new RandomAccessFile(destFile, "rw");
//        跳转到初始位置
            randomAccessFile.seek(start);
//        写入文件内容
            randomAccessFile.write(file.getBytes());
            randomAccessFile.close();
        } catch (IOException e) {
            return AjaxResult.isFail("上传失败！");
        }
        return AjaxResult.isOk();
    }

    //    前台修改资源
    @RequestMapping("/modifyFrontResource.do")
    @ResponseBody
    public AjaxResult modifyFrontResource(Resource resource, MultipartFile multiFiles, HttpSession session) {
        System.out.println(resource);
//        获取文件上传的路径
        CommonUtil.setContext(session.getServletContext());// 设置上下文
        String uploadPath = CommonUtil.getUploadPath();
        System.out.println("uploadPath=" + uploadPath);

        File dirfile = new File(uploadPath, Constant.RESOURCE_FILE);
//        资源文件：如果路径不存在，则创建
        if (!dirfile.exists()) {
            dirfile.mkdirs();
        }
//        获取文件名称
        String filename = multiFiles.getResource().getFilename();


//        判断文件是否存在
        File resourceFile = new File(dirfile, filename);
        long start = 0;// 记录资源文件初始位置
        if (resourceFile.exists()) {// 资源文件存在
            start = resourceFile.length();
        }

//        将资源信息添加到数据库
//        if(-1==resource.getChapter_id()){
//            return AjaxResult.isFail("请选择章节");
//        }
//        封装resource
        resource.setPath(Constant.RESOURCE_FILE + "/" + filename);
        resource.setOriginal_name(filename);
        resource.setFile_size(multiFiles.getSize());
        String[] type = multiFiles.getContentType().split("/");
        resource.setFile_type("." + type[type.length - 1]);
        if (null != session.getAttribute(Constant.SESSION_USER)) {
            User user = (User) session.getAttribute(Constant.SESSION_USER);
            resource.setUser_id(user.getId());
        }
        try {
            if (!resourceService.modifyFrontResource(resource)) {
                return AjaxResult.isFail("修改失败！");
            }
        } catch (ServiceException e) {
            return AjaxResult.isFail(e.getMessage());
        }
        return AjaxResult.isOk(start);
    }

    // 前台删除资源
    @RequestMapping("/removeFrontResource.do")
    @ResponseBody
    public AjaxResult removeFrontResource(Integer id) {
        try {
            if (resourceService.removeFrontResource(id)) {
                return AjaxResult.isOk("删除成功！");
            }
        } catch (ServiceException e) {
            e.printStackTrace();
        }
        return AjaxResult.isFail("删除失败！");
    }

    /*前台
checkResource(${res.id},'${chas.title}-${res.title}')
checkResource(resource_id,path)
资源校验方法
验证用户积分或金币是否足够
data:{"resource_id":resource_id,"path":path}
**/
    @RequestMapping("/checkup.do")
    @ResponseBody
    public AjaxResult checkGPAndResource(Integer resource_id, String path, HttpSession session) {
        AjaxResult result = new AjaxResult(true, "", null);
        //查询用户的金币/积分总数量
        //SESSION_USER
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        user = userService.selectDetailGPById(user.getId());
//        user = userService.selectDetailGPById(2);//测试数据
        int gold_count = user.getGold_count();
        int point_count = user.getPoint_count();
        Resource resource = resourceService.selectById(resource_id);
        //判断资源是否存在
        try {
            Properties properties = new Properties();
            properties.load(this.getClass().getClassLoader().getResourceAsStream("file.properties"));
            //src="${pageContext.request.contextPath}/upload/${resource.path}"//${chas.title}-${res.title}
            String resourcePath = session.getServletContext().getRealPath(properties.getProperty("resourcePath") + resource.getPath());
            File file = new File(resourcePath);
            if (!file.exists()) {
                result.setSuccess(false);
                result.setMsg("资源路径不存在！");
                return result;
            }
        } catch (IOException e) {
            result.setSuccess(false);
            result.setMsg(e.getMessage());
            return result;
        }
        int click_count = resourceService.selectClickCountById(resource_id);
        //判断是否是购买过资源
        UserResource userResource = new UserResource();
        userResource.setUserId(user.getId());
        userResource.setResourceId(resource_id);
        if (userResourceService.selectByUserIdAndResourceId(userResource)) {
            //更新最近查看资源的时间
            userResource.setUpdateDate(new Date());
            userResourceService.updateLastDateByUserIdAndResourceId(userResource);
            //更新资源点击量
            resourceService.updateClickCountById(resource_id, click_count + 1);
            result.setMsg("已拥有该资源，可以直接观看！");
            result.setObj(resource);
            return result;
        }
        //查询资源需消耗的金币/积分数量
        int cost_number = resource.getCost_number();
        int cost_type = resource.getCost_type();
        String type = cost_type == 0 ? "积分" : "金币";
        //判断余额是否足够
        if (cost_type == Constant.COST_TYPE_GOLD) {
            if (gold_count < cost_number) {
                result.setSuccess(false);
                result.setMsg("金币余额不足，无法查看资源信息");
                return result;
            }
        } else {
            if (point_count < cost_number) {
                result.setSuccess(false);
                result.setMsg("积分余额不足，无法查看资源信息");
                return result;
            }
        }
        //进行扣除与增加并更新数据库中数据
        System.out.println(user + ":" + resource);
        goldPointsService.updateGPInfoByUserId(user.getId(), resource.getUser().getId(), cost_number, cost_type);
        //将购买后的资源加入我的资源表中
        userResource.setCreateDate(new Date());
        userResource.setUpdateDate(new Date());
        userResourceService.insertMyResources(userResource);
        //更新资源点击量
        resourceService.updateClickCountById(resource_id, click_count + 1);
        //返回数据
        if (resource.getFile_type().equals(".mp4")) {
            result.setMsg("成功支付" + cost_number + type + "!即将进入播放页面...");
        } else {
            result.setMsg("成功支付" + cost_number + type + "!即将开始下载...");
        }
        result.setObj(resource);
//        session.setAttribute("data",result);//${data.obj.path}
        return result;
    }

    /*跳转
    前台：加载章节资源MP4视频
    showRs.do?course_id=`+course_id+`&resource_id=`+resource_id+`&path=`+path
    **/
    @RequestMapping("/showRs.do")
    public String showRS(HttpServletRequest request, HttpSession session) {
        System.out.println("showRs.do=================================");
        int course_id = Integer.parseInt(request.getParameter("course_id"));
        int resource_id = Integer.parseInt(request.getParameter("resource_id"));
        String path = request.getParameter("path");
        session.setAttribute("course_id", course_id);
        Resource resource = resourceService.selectById(resource_id);
        System.out.println(resource);//前台获取file_type
        session.setAttribute("resource", resource);
        session.setAttribute("path", path);
        return "redirect:/front_courseDetail";
    }

}
